<template>
  <div class="user-management-container">
    <!-- 1. 顶部当前用户信息卡片 -->
    <el-card class="user-profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>我的信息</span>
        </div>
      </template>
      <el-row :gutter="20" align="middle">
        <el-col :span="4" :xs="24" :sm="6" :md="4" style="text-align: center;">
          <el-avatar :size="80" :src="currentUser.avatarUrl" />
        </el-col>
        <el-col :span="14" :xs="24" :sm="18" :md="14">
          <h3>{{ currentUser.name }}</h3>
          <p class="user-info-item">
            <el-icon><Postcard /></el-icon> 编号: {{ currentUser.id }}
          </p>
          <p class="user-info-item">
            <el-tag :type="getRoleTagType(currentUser.role)" effect="light" round>
              <el-icon><User /></el-icon> {{ currentUser.role }}
            </el-tag>
          </p>
          <p class="user-info-item">
            <el-icon><Phone /></el-icon> {{ currentUser.phone }}
          </p>
        </el-col>
        <el-col :span="6" :xs="24" :sm="24" :md="6" class="action-buttons">
          <el-button type="primary" :icon="Edit" circle @click="handleEdit(currentUser, 'currentUser')" />
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(currentUser, 'currentUser')" />
        </el-col>
      </el-row>
    </el-card>

    <el-divider />

    <!-- 2. 表格控制区域 (代码无变化，保持原样) -->
    <div class="table-control-section">
      <div class="table-toggle-section">
        <h2>用户列表</h2>
        <el-switch
          v-model="showTable"
          size="large"
          inline-prompt
          active-text="显示"
          inactive-text="隐藏"
        />
      </div>

      <template v-if="showTable">
        <div v-if="isAdmin" class="table-wrapper">
          <el-form :inline="true" :model="filters" class="filter-container">
            <el-form-item label="姓名">
              <el-input v-model="filters.name" placeholder="模糊查询姓名" clearable :prefix-icon="Search" />
            </el-form-item>
            <el-form-item label="ID">
              <el-input v-model="filters.id" placeholder="查询ID" clearable :prefix-icon="Search" />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="filters.role" placeholder="按角色筛选" clearable class="role-select-filter">
                <el-option label="设备管理人员" value="设备管理人员" />
                <el-option label="维修人员" value="维修人员" />
                <el-option label="普通用户" value="普通用户" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="resetFilters" :icon="RefreshRight">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table 
            :data="paginatedData" 
            style="width: 100%" 
            border 
            stripe
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column prop="name" label="姓名" width="150" sortable="custom" />
            <el-table-column prop="role" label="角色" width="180">
              <template #default="scope">
                <el-tag :type="getRoleTagType(scope.row.role)">
                  {{ scope.row.role }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话" />
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row, 'tableUser')">
                  <el-icon><Edit /></el-icon> 修改
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row, 'tableUser')">
                  <el-icon><SwitchButton /></el-icon> 注销
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination-container"
          />
        </div>
        <el-alert
          v-else
          title="无权限访问"
          type="warning"
          description="抱歉，只有设备管理人员才能查看和管理用户列表。"
          show-icon
          :closable="false"
          class="permission-alert"
        />
      </template>
    </div>

    <!-- 修改用户信息的对话框 (代码无变化，保持原样) -->
    <el-dialog v-model="editDialogVisible" title="修改用户信息" width="500px">
      <el-form :model="editForm" ref="editFormRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="设备管理人员" value="设备管理人员"></el-option>
            <el-option label="维修人员" value="维修人员"></el-option>
            <el-option label="普通用户" value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Edit, 
  Delete, 
  Phone, 
  User, 
  SwitchButton, 
  Search, 
  RefreshRight,
  Postcard // 引入新图标
} from '@element-plus/icons-vue';

// --- 以下JS逻辑部分无变化，保持原样 ---

// 当前登录的用户信息 (可以修改 role 来测试权限)
const currentUser = reactive({
  id: 0, 
  name: '管理员',
  role: '设备管理人员', 
  phone: '13800138000',
  avatarUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
});
const showTable = ref(true);
const tableData = ref([]);
const filters = reactive({ name: '', id: '', role: '' });
const sortState = reactive({ prop: null, order: null });
const currentPage = ref(1);
const pageSize = ref(5);
const editDialogVisible = ref(false);
const editForm = reactive({ id: null, name: '', role: '', phone: '' });
const editingUserType = ref('');

onMounted(() => {
  const mockUsers = [
    { id: 1, name: '张三', role: '设备管理人员', phone: '13912345678', status: '正常' },
    { id: 2, name: '李四', role: '维修人员', phone: '13787654321', status: '正常' },
    { id: 3, name: '王五', role: '普通用户', phone: '13655558888', status: '正常' },
    { id: 4, name: '赵六', role: '普通用户', phone: '13599996666', status: '已注销' },
    { id: 5, name: '孙七', role: '维修人员', phone: '18812341234', status: '正常' },
    { id: 10, name: '周八', role: '普通用户', phone: '18678907890', status: '正常' },
    { id: 22, name: '吴九', role: '设备管理人员', phone: '17765436543', status: '正常' },
  ];
  for (let i = 23; i <= 50; i++) {
    mockUsers.push({ id: i, name: `用户${i}`, role: '普通用户', phone: `150${String(i).padStart(8, '0')}`, status: '正常' });
  }
  tableData.value = mockUsers;
});

const isAdmin = computed(() => currentUser.role === '设备管理人员');

const filteredData = computed(() => {
  let data = tableData.value;
  data = data.filter(user => {
    const matchName = filters.name ? user.name.toLowerCase().includes(filters.name.toLowerCase()) : true;
    const matchId = filters.id ? String(user.id).includes(filters.id) : true;
    const matchRole = filters.role ? user.role === filters.role : true;
    return matchName && matchId && matchRole;
  });
  if (sortState.prop && sortState.order) {
    data.sort((a, b) => {
      const valA = a[sortState.prop];
      const valB = b[sortState.prop];
      let comparison = 0;
      if (valA > valB) { comparison = 1; } 
      else if (valA < valB) { comparison = -1; }
      return sortState.order === 'ascending' ? comparison : -comparison;
    });
  }
  if (currentPage.value > 1 && data.length <= pageSize.value * (currentPage.value - 1)) {
    currentPage.value = 1;
  }
  return data;
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const getRoleTagType = (role) => {
  if (role === '设备管理人员') return 'primary';
  if (role === '维修人员') return 'warning';
  return 'info';
};

const resetFilters = () => { filters.name = ''; filters.id = ''; filters.role = ''; };
const handleSortChange = ({ prop, order }) => { sortState.prop = prop; sortState.order = order; };
const handleSizeChange = (val) => { pageSize.value = val; currentPage.value = 1; };
const handleCurrentChange = (val) => { currentPage.value = val; };
const handleEdit = (user, type) => {
  Object.assign(editForm, { id: user.id, name: user.name, role: user.role, phone: user.phone });
  editingUserType.value = type;
  editDialogVisible.value = true;
};
const handleDelete = (user, type) => {
  ElMessageBox.confirm(`确定要注销用户 "${user.name}" 吗？`, '警告', {
    confirmButtonText: '确定注销', cancelButtonText: '取消', type: 'warning',
  }).then(() => {
    if (type === 'tableUser') {
      const index = tableData.value.findIndex(u => u.id === user.id);
      if (index !== -1) { tableData.value.splice(index, 1); }
    } else if (type === 'currentUser') { console.log("注销当前用户..."); }
    ElMessage({ type: 'success', message: `用户 "${user.name}" 已注销` });
  }).catch(() => ElMessage({ type: 'info', message: '已取消操作' }));
};
const submitEdit = () => {
  if (editingUserType.value === 'currentUser') {
    Object.assign(currentUser, editForm);
  } else if (editingUserType.value === 'tableUser') {
    const index = tableData.value.findIndex(u => u.id === editForm.id);
    if (index !== -1) { tableData.value[index] = { ...tableData.value[index], ...editForm }; }
  }
  editDialogVisible.value = false;
  ElMessage.success('用户信息更新成功！');
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.user-profile-card { margin-bottom: 20px; }
.card-header { font-weight: bold; }
.user-profile-card h3 { margin: 0 0 10px; font-size: 1.5rem; color: #303133; }
.user-info-item { /* 统一p标签的样式 */
  margin: 8px 0;
  color: #606266;
  display: flex;
  align-items: center;
  font-size: 14px;
}
.user-info-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}
.action-buttons { text-align: right; }

@media (max-width: 768px) {
  .action-buttons { text-align: left; margin-top: 15px; }
}

.table-control-section {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-toggle-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.table-toggle-section h2 { margin: 0; font-size: 1.2rem; color: #303133; }
.filter-container { margin-bottom: 20px; }
.pagination-container { margin-top: 20px; display: flex; justify-content: flex-end; }
.permission-alert {
  margin-top: 20px;
}

.filter-container .role-select-filter {
  width: 180px;
}
</style>